<template>
  <div class="workbench-container">
    <van-notice-bar left-icon="volume-o" :text="rollingTips" class="workbench-notice" speed="50" :scrollable="true" />
    <div class="workbench-container-wrap">
      <div class="workbench-header">
        <template v-if="token">
          <div class="workbench-header-avatar" :style="{ backgroundImage: `url(${i_defaultAvatar})` }"></div>
          <div class="workbench-header-info">
            <div class="workbench-header__title">
              <div class="name">{{ account.userName }}</div>
              <div class="label">服务员</div>
            </div>
            <div class="workbench-header__subtitle">{{ currentDate }}</div>
          </div>
          <div class="workbench-header-control topup" @click="rechargeCodeShow = true">
            <img class="workbench-header__icon" :src="v_main_topup" alt="SVG Icon" />
            <div class="workbench-header__text">推广码</div>
          </div>
          <van-badge :content="content" :show-zero="false" max="99" class="workbench-header-badge">
            <div class="workbench-header-control" @click="router.push('/notice')">
              <img class="workbench-header__icon" :src="v_main_notice" alt="SVG Icon" />
              <div class="workbench-header__text">通知</div>
            </div>
          </van-badge>
        </template>

        <template v-else>
          <div class="workbench-header-avatar" :style="{ backgroundImage: `url(${i_logo})` }"></div>
          <div class="workbench-header-info">
            <div class="workbench-header__btn" @click="router.push('/login')">
              立即登录
            </div>
          </div>
        </template>
        <van-popover class="workbench-header-popover" v-model:show="showPopover" :actions="actions" theme="dark"
          placement="bottom-end" @select="onSelectPopover" overlay :overlay-style="{
          background: 'transparent'
        }">

          <template #reference>
            <div class="workbench-header-control">
              <img class="workbench-header__icon" :src="v_main_setting" alt="SVG Icon" />
              <div class="workbench-header__text">设置</div>
            </div>
          </template>
        </van-popover>
      </div>
      <div class="workbench-main">
        <div class="workbench-group daily">
          <div class="workbench-group-title">{{ dailyGroup.title }}</div>
            <div class="dailyService-box">
              <div class="first-row">
                <div class="openTabel" v-if="firstThreePermissions.includes('waiter-openRoom')" :class="firstThreePermissions.includes('waiter-openRoom') ? '' : 'menuDisable'" @click="onJump('open')">
                  <img class="open_icon" :src="i_menu_open" />
                  <div class="title">开台</div>
                </div>
                <div class="action-container" :class="openAuto ? '' : 'noPermission'">
                  <div class="item-action" v-if="firstThreePermissions.includes('waiter-reserve')" :class="firstThreePermissions.includes('waiter-reserve') ? '' : 'menuDisable'" @click="onJump('book/form')">
                    <img :src="i_menu_book" class="item-img" alt="">
                    <div class="item-title">预订</div>
                  </div>
                  <div class="item-action" v-if="firstThreePermissions.includes('waiter-retrievalNum')" @click="onJump('queue')" :class="firstThreePermissions.includes('waiter-retrievalNum') ? '' : 'menuDisable'">
                    <img :src="i_menu_queue" class="item-img" alt="">
                    <div class="item-title">取号</div>
                  </div>
                  <div class="item-action" v-if="firstThreePermissions.includes('waiter-storeWine')" @click="onJump('save')" :class="firstThreePermissions.includes('waiter-storeWine') ? '' : 'menuDisable'">
                    <img :src="i_menu_save" class="item-img" alt="">
                    <div class="item-title">存酒</div>
                  </div>
                  <div class="item-action" v-if="firstThreePermissions.includes('waiter-takeWine')" @click="onJump('take')" :class="firstThreePermissions.includes('waiter-takeWine') ? '' : 'menuDisable'">
                    <img :src="i_menu_take" class="item-img" alt="">
                    <div class="item-title">取酒</div>
                  </div>
                  <div class="item-action" v-if="firstThreePermissions.includes('waiter-guestCovery')" @click="onJump('recycle')" :class="firstThreePermissions.includes('waiter-guestCovery') ? '' : 'menuDisable'">
                    <img :src="i_menu_recycle" class="item-img" alt="">
                    <div class="item-title">客遗回收</div>
                  </div>
                  <div class="item-action" v-if="firstThreePermissions.includes('waiter-gift')" @click="onJump('sign')" :class="firstThreePermissions.includes('waiter-gift') ? '' : 'menuDisable'">
                    <img :src="i_menu_sign" class="item-img" alt="">
                    <div class="item-title">赠送</div>
                  </div>
                </div>
              </div>

              <div class="second-row">
                <div class="second-item-action"  :class="remainingPermissions.includes(item.menuName) ? '' : 'menuDisable'"  v-for="(item, index) in dailyGroup.list" :key="index" @click="onJump(item.name)">
                  <img class="item-img" :src="item.src" />
                  <div class="item-title">{{ item.meta.title }}</div>
                </div>
              </div>
            </div>
        </div>
        <div class="workbench-group manage">
          <div class="workbench-group-title" v-if="jytitleShow">{{ manageGroup.title }}</div>
          <div class="workbench-group-grid workbench-group-grid-news" :class="{'jt-not-flex':manageGroupLength.length == 1}">
            <div v-for="(item, index) in manageGroup.list" :key="index">
                <div class="workbench-group-item" :class="item.auto ? '' : 'menuDisable'" v-if="item.meta.title  !='无'"
                @click="onJump(item.name)">
                <img class="workbench-group__icon" :src="item.src" />
                <span class="workbench-group__text">{{ item.meta.title }}</span>
              </div>
              <div class="workbench-group-item" v-if="item.meta.title  =='无'" style="background: none;box-shadow: none;"></div>
            </div>
        
          </div>
        </div>
        <div class="workbench-group manage">
          <div class="workbench-group-title" v-if="sjtitleShow">{{ boardGroup.title }}</div>
          <div class="workbench-group-grid">
            <div class="workbench-group-item" :class="item.auto ? '' : 'menuDisable'"
              v-for="(item, index) in boardGroup.list" :key="index" @click="onJump(item.name,item?.path)">
              <img class="workbench-group__icon" :src="item.src" />
              <span class="workbench-group__text">{{ item.meta.title }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="cm-company-footer" style="position: relative; bottom: 0">
      癸卯兔科技发展集团 极兔妙创网络科技 技术支持
    </div>
  </div>


  <!-- 会员充值码弹窗 -->
  <RechargeCode v-if="rechargeCodeShow" v-model:show="rechargeCodeShow" />

  <!-- 联系客服弹窗 -->
  <z-popup v-model:show="serviceShow" title="联系客服" closeable>
    <div class="popup-service">
      <ul class="popup-service-list">
        <li class="popup-service-item" v-for="(v, k) in serviceList" :key="k">
          <div class="popup-service-label">{{ v.label }}</div>
          <div class="popup-service-value">{{ v.value }}</div>
          <img class="popup-service-icon" :src="v.icon" alt="SVG Icon" v-if="v.icon && v.label != '电话'"
            @click="onCopy(v.value)" />
          <a :href="`tel:${v.value}`" v-if="v.label == '电话'">
            <img class="popup-service-icon" :src="v.icon" alt="SVG Icon" v-if="v.icon" />
          </a>
        </li>
      </ul>
    </div>
  </z-popup>
</template>

<script setup>
import ls from '@/lib/ls'
import useAppStore from '@/store/app'
import useConfigStore from '@/store/config'
import axios from 'axios'
import dayjs from 'dayjs'
import { showToast } from 'vant'
import Api from '@/api'
import { closeWebSocket, initWebSocket, sendWebSocket } from '@/pkg/websocket'


import i_defaultAvatar from '@/assets/images/workbench/defaultAvatar.png'
import i_logo from '@/assets/images/common/logo.png'
import v_main_topup from '@/assets/svg/workbench/v_main_topup.svg'
import v_main_notice from '@/assets/svg/workbench/v_main_notice.svg'
import v_main_setting from '@/assets/svg/workbench/v_main_setting.svg'
import v_popover_password from '@/assets/svg/workbench/v_popover_password.svg'
import v_popover_help from '@/assets/svg/workbench/v_popover_help.svg'
import v_popover_about from '@/assets/svg/workbench/v_popover_about.svg'
import v_popover_tel from '@/assets/svg/workbench/v_popover_tel.svg'
import v_popover_logout from '@/assets/svg/workbench/v_popover_logout.svg'
import v_popover_tel_yellow from '@/assets/svg/workbench/v_popover_tel_yellow.svg'
import v_popover_copy from '@/assets/svg/workbench/v_popover_copy.svg'

import i_menu_open from '@/assets/images/workbench/i_menu_open.png'
import i_menu_book from '@/assets/images/workbench/i_menu_book.png'
import i_menu_queue from '@/assets/images/workbench/i_menu_queue.png'
import i_menu_take from '@/assets/images/workbench/i_menu_take.png'
import i_menu_save from '@/assets/images/workbench/i_menu_save.png'
import i_menu_recycle from '@/assets/images/workbench/i_menu_recycle.png'
import i_menu_sign from '@/assets/images/workbench/i_menu_sign.png'
import i_menu_onproduct from '@/assets/images/workbench/i_menu_onproduct.png'
import i_menu_statistics from '@/assets/images/workbench/i_menu_statistics.png'
import i_menu_rank from '@/assets/images/workbench/i_menu_rank.png'
import i_menu_performance from '@/assets/images/workbench/i_menu_performance.png'
import i_menu_onwine from '@/assets/images/workbench/i_menu_onwine.png'
import i_menu_onmember from '@/assets/images/workbench/i_menu_onmember.png'
import i_menu_onqueue from '@/assets/images/workbench/i_menu_onqueue.png'
import i_menu_abnormal from '@/assets/images/workbench/i_menu_abnormal.png'
import i_menu_collect from '@/assets/images/workbench/i_menu_collect.png'
import i_menu_order from '@/assets/images/workbench/i_menu_order.png'
import i_menu_bookList from '@/assets/images/workbench/i_menu_bookList.png'
import i_menu_send from '@/assets/images/workbench/i_menu_send.png'
import i_menu_change from '@/assets/images/workbench/i_menu_change.png'
import i_menu_pre_order from '@/assets/images/workbench/i_menu_pre_order.svg'
import i_menu_analysis from '@/assets/images/workbench/i_menu_analysis.png'
import i_menu_writeof from '@/assets/images/workbench/i_menu_write-of.png'
import eventBus from '@/utils/eventBus';
import packageJson from '../../../../package.json';


const appStore = useAppStore()
const configStore = useConfigStore()
const route = useRoute()
const router = useRouter()
const token = ref(ls.get('TOKEN'))
const account = ref(appStore.user_info)
const currentDate = ref(dayjs().format('YYYY-MM-DD'))
const currentTime = ref(dayjs())
const rechargeCodeShow = ref(false)
const serviceShow = ref(false)


const userinfoText = ref(ls.get('USER_INFO') ? ls.get('USER_INFO').purviewType + '  ' +  ls.get('USER_INFO').loginTime : '' )

const serviceList = [
  {
    label: '电话',
    value: '0591-22298919',
    icon: v_popover_tel_yellow,
    type: 'tel'
  },
  {
    label: '微信',
    value: 'wx997616997',
    icon: v_popover_copy,
    type: 'copy'
  },
  {
    label: 'QQ',
    value: '997616997',
    icon: v_popover_copy,
    type: 'copy'
  },
  {
    label: '邮箱',
    value: '997616997@qq.com',
    icon: v_popover_copy,
    type: 'copy'
  },
  {
    label: '地址',
    value: '福建省福州市晋安区化工路晋安三创中心11层',
    icon: '',
    type: ''
  }
]

const dailyGroup = ref({
  name: 'daily',
  title: '日常服务',
  list: [
    {
      menuName: 'waiter-takeWine',
      name: 'take',
      src: i_menu_take,
      auto: false,
      meta: {
        title: '取酒'
      }
    },
    {
      menuName: 'waiter-storeWine',
      name: 'save',
      src: i_menu_save,
      auto: false,
      meta: {
        title: '存酒'
      }
    },
    {
      menuName: 'waiter-guestCovery',
      name: 'recycle',
      src: i_menu_recycle,
      auto: false,
      meta: {
        title: '客遗回收'
      }
    },
    {
      menuName: 'waiter-gift',
      name: 'sign',
      src: i_menu_sign,
      auto: false,
      meta: {
        title: '赠送'
      }
    }
  ]
})

const manageGroup = {
  name: 'manage',
  title: '经营管理',
  list: [
    {
      menuName: 'waiter-call',
      name: 'onqueue',
      src: i_menu_onqueue,
      auto: false,
      meta: {
        title: '排队叫号'
      }
    },
    {
      menuName: 'waiter-reserveQuery',
      name: 'book',
      src: i_menu_bookList,
      auto: false,
      meta: {
        title: '预订查询'
      }
    },
    {
      menuName: 'waiter-orderQuery',
      name: 'statistics/orderlist',
      src: i_menu_order,
      auto: false,
      meta: {
        title: '订单查询'
      }
    },
    {
      menuName: 'waiter-member',
      name: 'onmember',
      src: i_menu_onmember,
      auto: false,
      meta: {
        title: '会员管理'
      }
    },
    {
      menuName: 'waiter-storeTakeWine',
      name: 'onwine',
      src: i_menu_onwine,
      auto: false,
      meta: {
        title: '存取酒管理'
      }
    },
    {
      menuName: 'waiter-goods',
      name: 'onproduct',
      src: i_menu_onproduct,
      auto: false,
      meta: {
        title: '商品管理'
      }
    },
    {
      menuName: 'waiter-cashierQuery',
      name: 'collect',
      src: i_menu_collect,
      auto: false,
      meta: {
        title: '收银查询'
      }
    },
    {
      menuName: 'waiter-errorPay',
      name: 'abnormal',
      src: i_menu_abnormal,
      auto: false,
      meta: {
        title: '异常消费'
      }
    },
    {
      menuName: 'waiter-giftQuery',
      name: 'send',
      src: i_menu_send,
      auto: false,
      meta: {
        title: '赠送查询'
      }
    },
    {
      menuName: 'waiter-refundChangeQuery',
      name: 'change',
      src: i_menu_change,
      auto: false,
      meta: {
        title: '退换菜查询'
      }
    },
    {
      menuName: 'waiter-perOrderQuery', // 临时过度 需要配置与正确获取权限接口 waiter-perOrderQueny 
      name: 'statistics/preorderlist',
      src: i_menu_pre_order,
      auto: false,
      meta: {
        title: '预点单查询'
      }
    },
    {
      menuName: 'waiter-hxrolQueny', // 临时过度 需要配置与正确获取权限接口 waiter-hxrolQueny 
      name: 'statistics/hxrollupQuery',
      src: i_menu_writeof,
      auto: false,
      meta: {
        title: '核销券查询'
      }
    }
  ]
}
const userCode = ref(ls.get('USER_INFO') ? ls.get('USER_INFO').userCode : '' )
//正常需要配置type1内置链接,type2外链,目前临时用title判别内外链接
const boardGroup = {
  name: 'board',
  title: '数据看板',
  list: [
    {
      menuName: 'waiter-business',
      name: 'statistics',
      src: i_menu_statistics,
      auto: false,
      meta: {
        title: '营业统计'
      }
    },
    {
      menuName: 'waiter-sales',
      name: 'rank',
      src: i_menu_rank,
      auto: false,
      meta: {
        title: '销售排行'
      }
    },
    {
      menuName: 'waiter-performance',
      name: 'performance',
      src: i_menu_performance,
      auto: false,
      meta: {
        title: '业绩查询'
      }
    },
    {
      menuName: 'waiter-analysis',
      name: 'exlinks-analysis',   // exlinks-analysis
      src: i_menu_analysis,
      path: `http://120.55.84.27:8000/webroot/decision/view/form?viewlet=loginReport%252FBI%25E5%2586%25B3%25E7%25AD%2596%25E5%2588%2586%25E6%259E%2590%25E7%25B3%25BB%25E7%25BB%259F.frm&op=h5#/form?viewlet=%2FloginReport%2Fdirectory.frm&username=${userCode.value}&navigationID=4abd1356bfdd72e2`,
      auto: false,
      meta: {
        title: '经营分析'
      }
    }
  ]
}

const onCopy = val => {
  if (window.isSecureContext) {
    navigator.clipboard.writeText(val).then(() => {
      showToast('复制成功')
    })
  } else {
    showToast('当前环境暂不支持复制功能')
  }
}
 
const onJump = function (name,path='') {
  const token = ls.get('TOKEN')
  if (token) {
    // 特殊情况临时处理 正常需要加个type识别内外链
    if (name === "exlinks-analysis") {
      const form = ls.get('LOGIN_VALUE')
      console.log(form,'userCode')
      let encodedPassword = encodeURIComponent(form.password);
      let url =  `https://bi.jtmckj.com/webroot/decision/login/cross/domain?validity=-1&fine_username=${form.username}&fine_password=${encodedPassword}`;
 
      function jsonp(url, callback) {
        // 生成一个随机的回调函数名
        const callbackName = "jsonp_" + Math.round(100000 * Math.random());
        // 创建一个全局回调函数，名字为随机生成的回调函数名
        window[callbackName] = function (data) {
          callback(data); // 调用用户传入的回调函数
          document.body.removeChild(script); // 请求完成后删除 script 标签
          delete window[callbackName]; // 清理全局变量
        };
        // 构建 URL，添加回调函数名参数
        const script = document.createElement("script");
        script.src =
          url + (url.indexOf("?") === -1 ? "?" : "&") + "callback=" +  callbackName;
        // 将 script 标签添加到页面上开始加载
        document.body.appendChild(script);
      }
      jsonp(url, function (response) {
        console.log(response); // 处理返回的数据
        if (response.status == "success") {
          // let openUrl = `https://bi.jtmckj.com/webroot/decision/view/form?viewlet=loginReport%252FBI%25E5%2586%25B3%25E7%25AD%2596%25E5%2588%2586%25E6%259E%2590%25E7%25B3%25BB%25E7%25BB%259F.frm&op=h5#/form?viewlet=%2FloginReport%2Fdirectory.frm&username=${userCode.value}&navigationID=1f4547eb3a63a0cd&orgCode=${ls.get('ORG_CODE')}`;
          let openUrl = `https://bi.jtmckj.com/webroot/decision/view/form?viewlet=loginReport%252Fdirectory.frm&orgCode=${ls.get('ORG_CODE')}&op=h5#/form`
          // setTimeout(()=>window.open(openUrl))
          
          setTimeout(()=>window.location.href = openUrl)
        }else{
          showToast('非BI用户，请联系管理员')
        }
      });
      return;
    } else if(name === 'performance') {
      Api.Common.AppObjProcess.Do({
        functionName: 'GetMarketUser',
        contentData: {groupCode:0}
      })
        .then(res=>{
          if(res.isLeader){

            const form = ls.get('LOGIN_VALUE')
                console.log(form,'userCode')
                let encodedPassword = encodeURIComponent(form.password);  // 对密码进行 URL 编码
                let url =  `https://bi.jtmckj.com/webroot/decision/login/cross/domain?validity=-1&fine_username=${form.username}&fine_password=${encodedPassword}`;

                function jsonp(url, callback) {
                  // 生成一个随机的回调函数名
                  const callbackName = "jsonp_" + Math.round(100000 * Math.random());
                  // 创建一个全局回调函数，名字为随机生成的回调函数名
                  window[callbackName] = function (data) {
                    callback(data); // 调用用户传入的回调函数
                    document.body.removeChild(script); // 请求完成后删除 script 标签
                    delete window[callbackName]; // 清理全局变量
                  };
                  // 构建 URL，添加回调函数名参数
                  const script = document.createElement("script");
                  script.src =
                    url + (url.indexOf("?") === -1 ? "?" : "&") + "callback=" +  callbackName;
                  // 将 script 标签添加到页面上开始加载
                  document.body.appendChild(script);
                }
                jsonp(url, function (response) {
                  console.log(response); // 处理返回的数据
                  if (response.status == "success") {
                    // let openUrl = `https://bi.jtmckj.com/webroot/decision/view/form?viewlet=loginReport%252FBI%25E5%2586%25B3%25E7%25AD%2596%25E5%2588%2586%25E6%259E%2590%25E7%25B3%25BB%25E7%25BB%259F.frm&op=h5#/form?viewlet=%2FloginReport%2Fdirectory.frm&username=${userCode.value}&navigationID=1f4547eb3a63a0cd&orgCode=${ls.get('ORG_CODE')}`;
                    let openUrl = null
                         openUrl = `https://bi.jtmckj.com:443/webroot/decision/view/form?viewlet=phone%252Fperformance%252F%25E4%25B8%259A%25E7%25BB%25A9%25E6%259F%25A5%25E8%25AF%25A2%25E6%258C%2589%25E6%258C%2587%25E5%25AE%259A%25E5%2595%2586%25E5%2593%2581.frm&op=h5&orgCode=${ls.get('ORG_CODE')}&op=h5#/form`
                    //   else if(ls.get('ORG_CODE') == '0024' || ls.get('ORG_CODE') == '0025') {
                    //      openUrl = `https://bi.jtmckj.com/webroot/decision/view/form?viewlet=phone%252Fperformance%252F%25E4%25B8%259A%25E7%25BB%25A9%25E6%259F%25A5%25E8%25AF%25A2.frm&op=h5&orgCode=${ls.get('ORG_CODE')}&op=h5#/form`
                    //  }
                    // setTimeout(()=>window.open(openUrl))
                    
                    setTimeout(()=>window.location.href = openUrl)
                  }else{
                    showToast('非BI用户，请联系管理员')
                  }
                });

          }else{
              const form = ls.get('LOGIN_VALUE')
                console.log(form,'userCode')
                let encodedPassword = encodeURIComponent(form.password);  // 对密码进行 URL 编码
                let url =  `https://bi.jtmckj.com/webroot/decision/login/cross/domain?validity=-1&fine_username=${form.username}&fine_password=${encodedPassword}`;

                function jsonp(url, callback) {
                  // 生成一个随机的回调函数名
                  const callbackName = "jsonp_" + Math.round(100000 * Math.random());
                  // 创建一个全局回调函数，名字为随机生成的回调函数名
                  window[callbackName] = function (data) {
                    callback(data); // 调用用户传入的回调函数
                    document.body.removeChild(script); // 请求完成后删除 script 标签
                    delete window[callbackName]; // 清理全局变量
                  };
                  // 构建 URL，添加回调函数名参数
                  const script = document.createElement("script");
                  script.src =
                    url + (url.indexOf("?") === -1 ? "?" : "&") + "callback=" +  callbackName;
                  // 将 script 标签添加到页面上开始加载
                  document.body.appendChild(script);
                }
                jsonp(url, function (response) {
                  console.log(response); // 处理返回的数据
                  if (response.status == "success") {
                    // let openUrl = `https://bi.jtmckj.com/webroot/decision/view/form?viewlet=loginReport%252FBI%25E5%2586%25B3%25E7%25AD%2596%25E5%2588%2586%25E6%259E%2590%25E7%25B3%25BB%25E7%25BB%259F.frm&op=h5#/form?viewlet=%2FloginReport%2Fdirectory.frm&username=${userCode.value}&navigationID=1f4547eb3a63a0cd&orgCode=${ls.get('ORG_CODE')}`;
                    let openUrl = null
                         openUrl = `https://bi.jtmckj.com/webroot/decision/view/form?viewlet=phone%252Fperformance%252FSalesPerformance.frm&op=h5#/form`
                    //   else if(ls.get('ORG_CODE') == '0024' || ls.get('ORG_CODE') == '0025') {
                    //      openUrl = `https://bi.jtmckj.com/webroot/decision/view/form?viewlet=phone%252Fperformance%252F%25E4%25B8%259A%25E7%25BB%25A9%25E6%259F%25A5%25E8%25AF%25A2.frm&op=h5&orgCode=${ls.get('ORG_CODE')}&op=h5#/form`
                    //  }
                    // setTimeout(()=>window.open(openUrl))
                    
                    setTimeout(()=>window.location.href = openUrl)
                  }else{
                    showToast('非BI用户，请联系管理员')
                  }
                });
          }
             
        })
           

    } else if(name === 'statistics') {
        if(ls.get('ORG_CODE') == '0024' || ls.get('ORG_CODE') == '0025') { 
              const form = ls.get('LOGIN_VALUE')
                console.log(form,'userCode')
                let encodedPassword = encodeURIComponent(form.password);  // 对密码进行 URL 编码
                let url =  `https://bi.jtmckj.com/webroot/decision/login/cross/domain?validity=-1&fine_username=${form.username}&fine_password=${encodedPassword}`;

                function jsonp(url, callback) {
                  // 生成一个随机的回调函数名
                  const callbackName = "jsonp_" + Math.round(100000 * Math.random());
                  // 创建一个全局回调函数，名字为随机生成的回调函数名
                  window[callbackName] = function (data) {
                    callback(data); // 调用用户传入的回调函数
                    document.body.removeChild(script); // 请求完成后删除 script 标签
                    delete window[callbackName]; // 清理全局变量
                  };
                  // 构建 URL，添加回调函数名参数
                  const script = document.createElement("script");
                  script.src =
                    url + (url.indexOf("?") === -1 ? "?" : "&") + "callback=" +  callbackName;
                  // 将 script 标签添加到页面上开始加载
                  document.body.appendChild(script);
                }
                jsonp(url, function (response) {
                  console.log(response); // 处理返回的数据
                  if (response.status == "success") {
                    // let openUrl = `https://bi.jtmckj.com/webroot/decision/view/form?viewlet=loginReport%252FBI%25E5%2586%25B3%25E7%25AD%2596%25E5%2588%2586%25E6%259E%2590%25E7%25B3%25BB%25E7%25BB%259F.frm&op=h5#/form?viewlet=%2FloginReport%2Fdirectory.frm&username=${userCode.value}&navigationID=1f4547eb3a63a0cd&orgCode=${ls.get('ORG_CODE')}`;
                    let openUrl = null
                    if(ls.get('ORG_CODE') == '0024' || ls.get('ORG_CODE') == '0025') {
                         openUrl = `https://bi.jtmckj.com/webroot/decision/view/report?viewlet=mobileReport%252Fbusinessmobile.cpt&op=h5#/report`
                     }
                    setTimeout(()=>window.location.href = openUrl)
                  }else{
                    showToast('非BI用户，请联系管理员')
                  }
                });
                return;
      } else {
        const form = ls.get('LOGIN_VALUE')
                console.log(form,'userCode')
                let encodedPassword = encodeURIComponent(form.password);  // 对密码进行 URL 编码
                let url =  `https://bi.jtmckj.com/webroot/decision/login/cross/domain?validity=-1&fine_username=${form.username}&fine_password=${encodedPassword}`;

                function jsonp(url, callback) {
                  // 生成一个随机的回调函数名
                  const callbackName = "jsonp_" + Math.round(100000 * Math.random());
                  // 创建一个全局回调函数，名字为随机生成的回调函数名
                  window[callbackName] = function (data) {
                    callback(data); // 调用用户传入的回调函数
                    document.body.removeChild(script); // 请求完成后删除 script 标签
                    delete window[callbackName]; // 清理全局变量
                  };
                  // 构建 URL，添加回调函数名参数
                  const script = document.createElement("script");
                  script.src =
                    url + (url.indexOf("?") === -1 ? "?" : "&") + "callback=" +  callbackName;
                  // 将 script 标签添加到页面上开始加载
                  document.body.appendChild(script);
                }
                jsonp(url, function (response) {
                  console.log(response); // 处理返回的数据
                  if (response.status == "success") {
                    // let openUrl = `https://bi.jtmckj.com/webroot/decision/view/form?viewlet=loginReport%252FBI%25E5%2586%25B3%25E7%25AD%2596%25E5%2588%2586%25E6%259E%2590%25E7%25B3%25BB%25E7%25BB%259F.frm&op=h5#/form?viewlet=%2FloginReport%2Fdirectory.frm&username=${userCode.value}&navigationID=1f4547eb3a63a0cd&orgCode=${ls.get('ORG_CODE')}`;
                    let openUrl = null
                    
                    openUrl = `https://bi.jtmckj.com/webroot/decision/view/form?viewlet=phone%252Fbusiness%252F%25E8%2590%25A5%25E4%25B8%259A%25E5%2588%2586%25E6%259E%2590.frm&op=h5#/form`
                     
                    setTimeout(()=>window.location.href = openUrl)
                  }else{
                    showToast('非BI用户，请联系管理员')
                  }
                });
                return;
      }


    } else{
      router.push({
        path: `/${name}`
      })
    } 
  } else {
    showToast('请先登录')
  }
}

const content = ref(0); 
onMounted(() => {
  content.value = ls.get('MSG_LIST') ? ls.get('MSG_LIST').length : 0
  console.log('content',content.value)
  eventBus.$on('myEventMsg', handleEvent);
}); 
onBeforeUnmount(() => {
  console.log('onBeforeUnmount...index')
  eventBus.$off('myEventMsg', handleEvent);
}); 
const handleEvent = (msg) => {
  content.value = msg;
};



const showPopover = ref(false)
const actions = [
  { text: '修改密码', icon: v_popover_password },
  // { text: '帮助中心', icon: v_popover_help },
  { text: '关于我们', icon: v_popover_about },
  { text: '联系客服', icon: v_popover_tel },
  { text: '退出登录', icon: v_popover_logout }
]
const onSelectPopover = function (action, index) {
  switch (index) {
    case 0:
      router.push('/changePassword')
      break
    case 1:
      router.push('/about')
      break
    case 2:
      serviceShow.value = true
      break
    case 3:
      const userInfo = ls.get('USER_INFO')
      console.log(userInfo);
      const wsObj = {
        msgReceivePage: "",
        msgType: "offline",
        platform: "2",//0：后台 1：PC 2：H5  3：小程序
        msgContent: {
          userCode: userInfo.orgCode
        }
      }
      sendWebSocket(wsObj)
      appStore.Logout()
      break
  }
}
const jytitleShow = ref(true)
const sjtitleShow = ref(true)
const openAuto = ref(false)
const reserveAuto = ref(false)
const takeNum = ref(false)

const isNewVersion = ref(1)

const firstThreePermissions = ref([])
const remainingPermissions = ref([])

const manageGroupLength = ref([])
const GetUserMenu = () => {
  // let appVersion = window.localStorage.getItem("gmtappVersion")
  // if(appVersion && appVersion == packageJson.version){
  //   isNewVersion.value = 1
  // }else{
  //   isNewVersion.value = 0
  // }
  let orgCode = ls.get('ORG_CODE')
    if(!orgCode){
      showToast('请重新登陆')
      setTimeout(() => {
        router.push({
            path: '/login'
        })
      }, 2000);
     
    return
  }
  Api.Common.AppObjProcess.Do({
    functionName: 'GetUserMenu',
    contentData: {isNewVersion:isNewVersion.value}
  }).then(res => {
    console.log(dayjs().format('YYYY-MM-DD'));
    console.log('GetUserMenu',res);
    ls.set('userMenu', res.result.split(','))
    console.log(ls.get('userMenu'),'userMenu---');
    
    // 假设 ls.get('userMenu') 返回用户的权限列表
const userMenuPermissions = ls.get('userMenu');
console.log(userMenuPermissions, 'userMenuPermissions');

// 用于存储按钮权限和 dailyGroup 权限
const updatedPermissions = [];

// 1.2 检查并更新按钮权限
userMenuPermissions.forEach(e => {
  if (e === 'waiter-openRoom') {
    openAuto.value = true;
    updatedPermissions.push('waiter-openRoom');
  }
  if (e === 'waiter-reserve') {
    reserveAuto.value = true;
    updatedPermissions.push('waiter-reserve');
  }
  if (e === 'waiter-retrievalNum') {
    takeNum.value = true;
    updatedPermissions.push('waiter-retrievalNum');
  }
});

// 1.3 处理 dailyGroup 的权限
const updatedDailyGroup = dailyGroup.value.list.map(item => {
  // 如果 userMenu 中存在此项权限，则设置 item.auto 为 true
  if (userMenuPermissions.includes(item.menuName)) {
    item.auto = true;
    updatedPermissions.push(item.menuName);  // 将此权限存入更新的权限数组
  } else {
    item.auto = false;
  }
  return item;
});

  console.log(updatedDailyGroup, 'updatedDailyGroup');
  console.log(updatedPermissions, 'updatedPermissions');

// 计算权限只算 updatedPermissions 数组里的权限
const permissionsToDisplay = updatedPermissions.filter(permission => {
  // 只保留存在于 updatedPermissions 中的权限
  return updatedPermissions.includes(permission);
});

console.log(permissionsToDisplay, '日常服务权限列表');

if (Array.isArray(permissionsToDisplay) && permissionsToDisplay.length > 0) {
    // 获取前3个元素，确保数组长度至少为 3
      if(openAuto.value == true) {
        firstThreePermissions.value = permissionsToDisplay.slice(0, 3);
      } else {
        firstThreePermissions.value = permissionsToDisplay.slice(0, 2);
      }
      console.log(firstThreePermissions.value, 'firstThreePermissions1');  //2个
    // 获取剩余的元素
    remainingPermissions.value = permissionsToDisplay.slice(2);
    console.log(remainingPermissions.value, 'remainingPermissions');
    
    if(remainingPermissions.value.length > 0) {
           remainingPermissions.value = remainingPermissions.value.filter(item => !firstThreePermissions.value.includes(item));
    }
      

    // 检查 firstThreePermissions 是否已经有足够的权限
    if (firstThreePermissions.value.length < 3) {
       if(openAuto.value == true) {
       // 从 remainingPermissions 中补充权限，最多补充 2 个
        const additionalPermissions = remainingPermissions.value.slice(0, 2);

        // 更新 firstThreePermissions
        firstThreePermissions.value = firstThreePermissions.value.concat(additionalPermissions);

        // 更新 remainingPermissions，去除已添加的权限
        remainingPermissions.value = remainingPermissions.value.slice(2);

        console.log('更新后的first', firstThreePermissions.value);
        console.log('更新remainingPermissions:', remainingPermissions.value);
       } 
    
    }
}


    // 经营管理
    manageGroup.list.forEach(item => {
      ls.get('userMenu').map(e => {
        if (e == item.menuName) {
          item.auto = true
        }
      })
    })
   
    manageGroupLength.value = manageGroup.list.filter(item=>item.auto)

    console.log(manageGroup.list,'manageGroup');
     if(manageGroup.list.length == 5 || manageGroup.list.length == 8  || manageGroup.list.length == 11) {
          manageGroup.list.push({
          menuName: manageGroup.list[0].menuName,
          auto: true,
          meta: {
            title: '无'
          }
        })
     }
  
    
    if (manageGroup.list.every(item => item.auto == false)) {
        jytitleShow.value = false;  
    }
    

    // 数据看板
    boardGroup.list.forEach(item => {
      ls.get('userMenu').map(e => {
        if (e == item.menuName) {
          item.auto = true
        }
      })
    })
    console.log(boardGroup.list);
    
    if (boardGroup.list.every(item => item.auto == false)) {
        sjtitleShow.value = false;  
    }
  
  }).catch(err=>{
    console.log(err);
    
    if(err == 'ApiError: 版本已更新，请刷新页面'){
      alert('请刷新页面获取最新版本，或者重新进入https://jtmckj.com:8081/')
      location.reload()
    }
  })
}




const autoForm = ref([
  {
    title: 'waiter-openRoom', // 开台
    auto: false
  },
  {
    title: 'waiter-reserve', // 预订
    auto: false
  },
  {
    title: 'waiter-retrievalNum', // 取号
    auto: false
  },

])

const rollingTips = ref('')
// 获取基础配置信息
const GetBaseInfo = () => {
  let orgCode = ls.get('ORG_CODE')
        if(!orgCode){
          showToast('请重新登陆')
            return
        }
  Api.Common.AppObjProcess.Do({ functionName: 'GetBaseConfigInfo', contentData: { orgCode: ls.get('ORG_CODE') } }).then(res => {
    rollingTips.value = res.RollingTips
    // 每次回到首页 都会刷新GetBaseInfo接口 跟新-默认按当前营业日查询（取报表时间）
    appStore.setReportTime(res.orgReportStartTime, res.orgReportEndTime)
    ls.set('LOGO',res.orgLogo)
  })
}

const onInit = () => {
  GetUserMenu()
  GetBaseInfo()
 
  const conBtn = ls.get('CONREOL_AUT')
  console.log(conBtn);
}
onInit()

// ----------------------------------------------- 长链接 ----------------------------------------------------------
// 连接设备  （具体路径和后端规定）
// const connectMsg = () => {
//   if (!configStore.isConnected) {
//     let toIp = import.meta.env.VITE_WS
//     configStore.connect()
//     initWebSocket(toIp)
//   }
// }
// const userInfo = ls.get('USER_INFO')
// if(userInfo){
//   connectMsg()
// }


// // 设备断开
// const closeWs = () => {
//   if (configStore.isConnected) {
//     closeWebSocket()
//     configStore.disconnect()
//   }
// }

</script>

<style scoped lang="scss">
.workbench-notice {
  padding: 7px 16px;
  font-size: 12px;
  font-family: PingFang SC;
  font-weight: 500;
  color: #ffeecc;
  line-height: 12px;
  background-color: rgba(51, 51, 51, 0.8);
  height: 30px;
}

.workbench-container {
  height: 100%;
  // background: #17171a;
  overflow-y: scroll;
  position: relative;
  display: flex;
  flex-direction: column;
  min-height: 100%;

  &-wrap {
    flex-grow: 1;
    padding: 4px 20px 0;
  }

  .workbench-header {
    display: flex;
    align-items: center;
    justify-content: space-between;

    &-avatar {
      width: 40px;
      height: 40px;
      background-size: 100% 100%;
    }

    &-info {
      padding-left: 8px;
      flex: 1;
    }

    &-control {
      &.topup {
        margin-right: 11px;
      }
    }

    &__title {
      display: flex;
      align-items: center;

      .name {
        // width: 120px;
        font-size: 16px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #ffffff;
        line-height: 16px;
        white-space: nowrap;
        /* 不换行 */
        overflow: hidden;
        /* 超出部分隐藏 */
        text-overflow: ellipsis;
        /* 超出部分显示省略号 */
      }

      .label {
        padding: 4px;
        border-radius: 2px;
        font-size: 12px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #666666;
        line-height: 12px;
        transform: scale(0.9);
        margin-left: 6px;
        border: 1px solid #333333;
        white-space: noWrap;
      }
    }

    &__subtitle {
      padding-top: 5px;
      font-size: 12px;
      font-family: PingFang SC;
      font-weight: 500;
      color: #999999;
      line-height: 12px;
    }

    &__btn {
      width: 70px;
      border: 1px solid #665f52;
      border-radius: 4px;
      padding: 5px 0;
      font-size: 14px;
      font-family: PingFang SC;
      font-weight: 500;
      color: #ffeecc;
      line-height: 14px;
      text-align: center;
    }

    &__icon {
      display: block;
      width: 20px;
      height: 20px;
      margin: auto;
    }

    &__text {
      padding-top: 6px;
      font-size: 12px;
      font-family: PingFang SC;
      font-weight: 500;
      color: #cccccc;
      line-height: 12px;
      white-space: noWrap;
    }
  }

  .workbench-main {
    padding-bottom: 50px;

    .workbench-group {
      padding: 30px 0 0 0;

      &.daily {
        .workbench-group-item {
          padding: 23px 0 23px 20px;
        }

        .workbench-group__text {
          font-size: 22px;
        }

        .workbench-group__icon {
          width: 30px;
          height: 30px;
        }

        .menuDisable {
          display: none;
          filter: grayscale(100%);
          pointer-events: none;
        }
      }

      &.manage {
        .workbench-group-item {
          padding: 18px 0 18px 12px;
        }

        .workbench-group__text {
          font-size: 18px;
        }

        .workbench-group__icon {
          width: 24px;
          height: 24px;
        }

        .menuDisable {
          display: none;
          filter: grayscale(100%);
          pointer-events: none;
        }
      }

      &-title {
        font-size: 16px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #ffd57f;
        line-height: 16px;
        text-align: left;
      }

      &-grid {
        display: flex;
        justify-content: space-between;
        flex-wrap: wrap;
        padding-top: 10px;
      }

      &-row {
        width: 100%;
      }

      &-col {
        display: flex;
        justify-content: space-between;

        &-left {}

        &-right {
          display: flex;
          flex-direction: column;
        }
      }

      &-item {
        margin-top: 10px;
        background: #28282e;
        box-shadow: 0px 5px 8px 0px rgba(3, 1, 13, 0.46);
        border-radius: 6px;
        width: 162px;
        display: flex;
        align-items: center;
        margin-top: 10px;
        cursor: pointer;

        &.large {
          height: 162px;
          display: block;
          padding-top: 30px;
          padding-left: 0px !important;

          .workbench-group__icon {
            width: 44px;
            height: 44px;
            margin: auto;
          }

          .workbench-group__text {
            font-size: 30px;
            text-align: center;
            display: block;
            padding-top: 24px;
            margin-left: 0;
          }
        }
      }

      &__icon {
        display: block;
      }

      &__text {
        font-family: PingFang SC;
        font-weight: 500;
        color: #ffeecc;
        line-height: 22px;
        margin-left: 12px;
      }
    }
  }
}

.workbench-header-popover {
  :deep(.van-popover__arrow) {
    color: #333340;
  }

  :deep(.van-popover__content) {
    background-color: #333340;
    color: #fefefe;
    width: 120px;
  }

  :deep(.van-popover__action) {
    height: 47px;
    padding: 0 0 0 10px;
  }
}

.workbench-header-badge {
  margin-right: 18px;

  :deep(.van-badge) {
    border: 0;
    font-size: 12px;
    line-height: 12px;
    padding: 2px 4px;
    transform: scale(0.83);
    top: -5px;
    right: -8px;
  }
}

.popup-service {
  padding: 0 12px;
  width: 333px;

  &-list {
    padding-bottom: 21px;
  }

  &-item {
    padding-top: 24px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  &-label {
    font-size: 16px;
    font-family: PingFang SC;
    font-weight: 500;
    color: #cccccc;
    line-height: 16px;
  }

  &-value {
    flex: 1;
    text-align: right;
    font-size: 16px;
    font-family: PingFang SC;
    font-weight: 500;
    color: #ffffff;
    line-height: 21px;
    max-width: 223px;
  }

  &-icon {
    display: block;
    width: 20px;
    height: 20px;
    margin-left: 12px;
  }
}



.dailyService-box {
  margin-top: 20px;
  display: flex;
  flex-direction: column; /* 上下排列 */
  gap: 10px; /* 盒子之间的间隙 */

  .first-row,
.third-row {
  display: flex;
  gap: 10px; /* 每个项之间的间隙 */
}
.second-row{
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  // gap: 10px; /* 每个项之间的间隙 */
}

.openTabel {
  height: 162px; /* openTabel 的高度 */
  background: #29292E;
  box-shadow: 0px 5px 8px 0px rgba(3,1,13,0.46);
  border-radius: 6px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex: 1; /* 让开台占满剩余空间 */
}

.open_icon {
  width: 44px;
  height: 44px;
  margin-bottom: 24px;
}

.title {
  font-weight: 500;
  font-size: 30px;
  color: #FFEECC;
}

.action-container {
  display: flex;
  flex-direction: column; /* 垂直排列预订和取号 */
  gap: 10px; /* 上下间距 */
  flex: 1; /* 让它占据剩余空间 */
}

.item-action {
  display: flex;
  align-items: center;
  justify-content: center;
  // width: 162px;
  height: 76px;
  background: #28282E;
  box-shadow: 0px 5px 8px 0px rgba(3,1,13,0.46);
  border-radius: 6px;
}
.second-item-action {
  width: 48.8%;
  display: flex;
  align-items: center;
  justify-content: center;
  // width: 162px;
  height: 76px;
  background: #28282E;
  box-shadow: 0px 5px 8px 0px rgba(3,1,13,0.46);
  border-radius: 6px;
  margin-bottom: 10px;
}

.item-img {
  width: 30px;
  height: 30px;
}

.item-title {
  margin-left: 12px;
  font-weight: 500;
  font-size: 22px;
  color: #FFEECC;
}

}

.grid-news {
  gap: 5px 15px;
}


.menuDisable {
      display: none;
      filter: grayscale(100%);
      pointer-events: none;
}
.noPermission {
  display: contents !important;
  .item-action {
    width: 50%;
   
  }
}

.workbench-group-grid-news {
     .workbench-group-item {
      // width: 48.5% !important;
     }
}
.jt-not-flex {
  display: flow-root !important;
}
</style>
